package com.jinbai.servlet;

import com.jinbai.dao.UserDao;
import com.jinbai.model.User;
import com.mysql.cj.Session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || username.trim().isEmpty()) {
            resp.sendRedirect("/login.html");
            return;
        }
        if (password == null || password.trim().isEmpty()) {
            resp.sendRedirect("/login.html");
            return;
        }
        UserDao userDao = new UserDao();
        User user = userDao.getUserByUsernameAndPassword(username, password);
        if (user == null) {
            resp.sendRedirect("/register.html");
            return;
        }
        HttpSession session = req.getSession();
        session.setAttribute("currentUser", user);
        resp.sendRedirect("/blog_list.html");
    }
}
